package com.xzkj.ad;

import android.util.Base64;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Description:
 * Data：2022/4/16-下午3:28
 * Author: liujie
 */
public class SecretUtil {
    /**
     * 包名转md5 32位
     */
    public static String secretKey = "0aeae375ee65969b2d04b4ce659b2eca";
    /**
     * 先AES加密，再Base64编码
     *
     * @param input
     * @return
     */
    public static String encryptAESAndEncodeBase64(String input) {
        if (input != null) {
            try {
                SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
                Cipher encryptCipher = Cipher.getInstance("AES/CFB/NoPadding");
                encryptCipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(new byte[encryptCipher.getBlockSize()]));
                // 必须用 ISO_8859_1 编码方式，否则 String 和 byte[] 转换会有问题，影响加解密结果
                byte[] newByte = encryptCipher.doFinal(input.getBytes(StandardCharsets.ISO_8859_1));
                return Base64.encodeToString(newByte, Base64.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return input;
    }

    /**
     * 先Base64解码，再AES解密
     *
     * @param input
     * @return
     */
    public static String decodeBase64AndDecryptAES(String input) {
        if (input != null) {
            try {
                SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
                Cipher decryptCipher = Cipher.getInstance("AES/CFB/NoPadding");
                decryptCipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(new byte[decryptCipher.getBlockSize()]));
                // 必须用 ISO_8859_1 编码方式，否则 String 和 byte[] 转换会有问题，影响加解密结果
                byte[] newByte = decryptCipher.doFinal(Base64.decode(input, Base64.DEFAULT));
                return new String(newByte, StandardCharsets.ISO_8859_1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return input;
    }
}
